1137. N-th Tribonacci Number
1. Question
The Tribonacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given n
, return the value of Tn.
2. Examples
Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:
Input: n = 25
Output: 1389537
3. Constraints
0 <= n <= 37
- The answer is guaranteed to fit within a 32-bit integer, ie.
answer <= 2^31 - 1
.
4. References
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/n-th-tribonacci-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
5. Solutions
class Solution {
public int tribonacci(int n) {
int[] arr = {0, 1, 1, 0};
if (n <= 2) {
return arr[n];
}
for (int i = 2; i < n; i++) {
arr[3] = arr[0] + arr[1] + arr[2];
arr[0] = arr[1];
arr[1] = arr[2];
arr[2] = arr[3];
}
return arr[3];
}
}
class Solution {
public int tribonacci(int n) {
int a = 0;
int b = 1;
int c = 1;
int d = 0;
if (n < 2) {
return n;
}
if (n == 2) {
return 1;
}
for (int i = 3; i <= n; i++) {
d = a + b + c;
a = b;
b = c;
c = d;
}
return d;
}
}